import { reqLogin, reqGetUserInfo, reqGetUserDetailById } from '@/api/user'
import { resetRoute } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'
const state = {
  token: getToken(),
  userInfo: {}
}

const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  setUserInfo(state, newInfo) {
    state.userInfo = newInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  },
  removeToken(state) {
    state.token = null
    removeToken()
  }
}

const actions = {
  async login(context, data) {
    const res = await reqLogin(data)
    context.commit('setToken', res.data)
    return res.data
  },

  async getUserInfo(context) {
    const { data: data1 } = await reqGetUserInfo(state.token)
    const { data: data2 } = await reqGetUserDetailById(data1.userId)
    const baseResult = {
      ...data1, ...data2
    }
    context.commit('setUserInfo', baseResult)
    return baseResult
  },

  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
    resetRoute()
    context.commit('permission/setRoutes', [], { root: true })
  }
}

const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters

}
